/*
 This file is part of BTStracker
		
    BTStracker is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    BTStracker is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Foobar.  If not, see <http://www.gnu.org/licenses/>.	
	author: azbest.pro (azbest.pro@gmail.com)
*/
package pl.vdl.azbest.mremote.com;

import java.io.IOException;
import java.io.OutputStream;
import java.util.logging.Logger;

import pl.vdl.azbest.log.LoggingTheGathering;

class CSCommunicate implements CState {
	private Logger logger = Logger.getLogger(getClass().getName());

	private CConnect conn;
	{
		LoggingTheGathering.addPath(getClass().getName());
	}

	public CSCommunicate(CConnect conn) {
		this.conn = conn;
	}

	public void connect() {
		// TODO Auto-generated method stub

	}

	public void disconnect() {
		conn.setState(CommState.CONNECTED,
				"You cannot disconnect while communicating ");

	}

	public void error() {
		// TODO Auto-generated method stub

	}

	public void timeout() {
		// TODO Auto-generated method stub

	}

	public synchronized void performWriting(final String line) {

		Thread t = new Thread(new SerialPortWriter(line));
		t.start();
		// System.out.println("COMMAND Send");
	}

	public void write(final String line) {
		// do nothing for security and simplicity sake
		System.err.println("Dirty to COMM write !");
	}

	public void openCommunication() {
		// TODO Auto-generated method stub

	}

	public void closeCommunication() {
	}

	public void perform() {
	}

	class SerialPortWriter implements Runnable {
		String line;

		public SerialPortWriter(String line) {
			this.line = line;
		}

		public void run() {
			Thread.currentThread().setName("SerialPortWriter");
			// System.out.println("Command: " + line + " from thread =="
			// + Thread.currentThread().getName());
			String line2 = line.trim();
			line2 += System.getProperty("line.separator");
			String line3 = line2;
			OutputStream os = CSCommunicate.this.conn.getPortOutputstream();
			String progress = "Writing.";
			try {
				char[] cx = line3.toCharArray();
				for (char cv : cx) {
					os.write(cv);
					// System.out.println(progress+cv);
					progress += ".";
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			conn.setState(CommState.CONNECTED, "", conn.sConnected);

		}
	}

}
